#include <stdio.h>
#include <math.h>
#include <GL/glut.h>
#include "Camera.h"

#define M_PI 3.14159265358979323846
#define M_PI_2 1.57079632679489661923

void Camera::Init(){

	/*
	(15, 0, 15)
	(0, 25, -15)

	y + ly = 25 + sin(pitch) = 0;
	pitch = sin(-25);

	x + lx = 0 + cos(yaw)*cos(pitch) = 15
	yaw = acos(15/cos(pitch))
	*/
	pitch = -0.75;
	yaw = 70;

	x = 10.0f;
	y = 18.0f;
	z = -8.0f; //position of camera (eye)

	deltaAngle = 0.0; // additional angle change when dragging
}

void Camera::Update(){
	lx = cos(yaw) * cos(pitch);
	ly = sin(pitch);
	lz = sin(yaw) * cos(pitch);

	strafe_lx = cos(yaw - M_PI_2);
	strafe_lz = sin(yaw - M_PI_2);

	lookx = x + lx;
	looky = y + ly;
	lookz = z + lz;

	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	gluLookAt(x, y, z,
		lookx, looky, lookz,
		0.0f,1.0f,0.0f);

}



void Camera::Reset(){
	Init();
	Update();
}

float Camera::GetX(){
	return x;
}

float Camera::GetY(){
	return y;
}

float Camera::GetZ(){
	return z;
}

float Camera::GetYaw()
{
	return yaw;
}


void Camera::RotateYaw(float angle)
{
	yaw += angle*ROTATION_SPEED;

	Update();
}

void Camera::RotatePitch(float angle)
{
    const float limit = 89.0 * M_PI / 180.0;

	pitch -= angle*ROTATION_SPEED;

    if(pitch < -limit)
        pitch = -limit;

    if(pitch > limit)
        pitch = limit;

	Update();
}

const float Camera::INCR = 0.25;
const float Camera::ROTATION_SPEED = M_PI/180*0.02;